<template>
  <el-dialog
    :title="this.mode === 'add' ? '新增角色' : '编辑角色'"
    :visible="isShow"
    @close="close"
  >
    <el-form ref="form" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model.trim="form.description" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { sysRolePost, sysRolePut } from '@/api/setting.js'
export default {
  name: 'DialogItem',
  props: {
    isShow: {
      type: Boolean,
      default: false
    },
    roles: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      form: {
        name: '',
        description: ''
      },
      initForm: '',
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              let res = ''
              if (this.mode === 'add') {
                res = this.roles.some((item) => {
                  return item.name === value
                })
              } else {
                res = this.roles.some((item) => {
                  return item.name === value && item.id !== this.form.id
                })
              }
              res ? callback(new Error('不能输入已经存在角色名')) : callback()
            },
            trigger: 'blur'
          }
        ],
        description: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      mode: 'add'
    }
  },
  created() {
    this.initForm = JSON.parse(JSON.stringify(this.form))
  },
  methods: {
    // 关闭弹窗
    close() {
      this.$emit('update:isShow', false)
      this.$refs.form.resetFields()
      this.form = JSON.parse(JSON.stringify(this.initForm))
    },
    // 弹框确定点击
    submit() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          if (this.mode === 'add') {
            // 新增
            await sysRolePost(this.form)
            this.$emit('pageChange', 1)
          } else {
            // 编辑
            await sysRolePut(this.form)
            this.$emit('getRole')
          }
          this.$message.success(
            this.mode === 'add' ? '新增角色成功' : '编辑角色成功'
          )
          this.close()
        }
      })
    }
  }
}
</script>

<style></style>
